<?php

// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------


namespace app\index\middleware;

use app\Request;
use app\service\jwt\IndexJwtService;
use Firebase\JWT\ExpiredException;
use think\exception\ValidateException;
use think\facade\Db;
use think\Response;
use Throwable;
use think\facade\Cache;

class UserTokenMiddleware extends BaseMiddleware
{

    /**
     * @param Request $request
     * @return array|void
     * @throws Throwable
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function before(Request $request)
    {
        $force = $this->getArg(0, true);
        try {
            $token = trim($request->header('X-Token'));
            //判断是否有token
            if (!$token || $token ==''){
                return ['status'=>100,'msg'=>'请登录'];
            }
            if (strpos($token, 'Bearer') === 0)
                $token = trim(substr($token, 6));
            $service = new IndexJwtService();
            //判断是否有缓存token
            $checkToken = Cache::get('user_' . $token);
            if(!$checkToken) return ['status'=>100,'msg'=>'请登录'];
            try {
                $checkInfo = $service->checkToken($token);
                if($checkInfo['status'] != 200){
                    return $checkInfo;
                }
            } catch (ExpiredException $e) {
                return ['status'=>100,'msg'=>'token 已过期'];
            }
            $payload = $checkInfo['data'];
            if ('user' != $payload['aud'])
                return ['status'=>100,'msg'=>'无效的 token'];
            //获取用户信息
            $user = Db::table('jy_user')->where('id',$payload['data']->user_id)->find();
            if (!$user)
                return ['status'=>100,'msg'=>'账号不存在'];
            if (!$user['status'])
                return ['status'=>100,'msg'=>'账号已被禁用'];
        } catch (Throwable $e) {
            if ($force)
                throw  $e;
            $request->macro('isLogin', function () {
                return  ['status'=>100,'msg'=>'请登录'];
            });
            $request->macros(['tokenInfo', 'uid', 'userInfo', 'token'], function () {
                return ['status'=>100,'msg'=>'请登录'];
            });
            return  ['status'=>100,'msg'=>'请登录'];
        }
        $service->updateToken($token);

        $request->macro('isLogin', function () {
            return true;
        });
        $request->macro('tokenInfo', function () use (&$payload) {
            return $payload;
        });
        $request->macro('token', function () use (&$token) {
            return $token;
        });
        $request->macro('uid', function () use (&$user) {
            return $user['id'];
        });
        $request->macro('userInfo', function () use (&$user) {
            return $user;
        });
    }

    public function after(Response $response)
    {
        // TODO: Implement after() method.
    }
}